"""
性能监控模块
提供系统性能指标收集和分析
"""

import time
import psutil
import threading
from typing import Dict, Any, List
from dataclasses import dataclass
from datetime import datetime
import logging

@dataclass
class PerformanceMetrics:
    """性能指标数据类"""
    timestamp: datetime
    cpu_percent: float
    memory_percent: float
    memory_used_mb: float
    disk_io_read_mb: float
    disk_io_write_mb: float
    processing_time: float
    files_processed: int
    files_generated: int

class PerformanceMonitor:
    """性能监控器"""
    
    def __init__(self, config: Dict[str, Any]):
        """初始化性能监控器"""
        self.config = config
        self.logger = logging.getLogger('image_cropping_system')
        
        # 监控配置
        self.enabled = config.get('performance', {}).get('monitoring_enabled', True)
        self.interval = config.get('performance', {}).get('monitoring_interval', 5)
        self.max_history = config.get('performance', {}).get('max_history', 1000)
        
        # 性能数据
        self.metrics_history: List[PerformanceMetrics] = []
        self.start_time = time.time()
        self.processing_start_time = None
        
        # 监控线程
        self.monitor_thread = None
        self.stop_monitoring = threading.Event()
        
        if self.enabled:
            self.start_monitoring()
            self.logger.info("性能监控已启动")
    
    def start_monitoring(self) -> None:
        """启动性能监控"""
        if not self.enabled:
            return
        
        self.stop_monitoring.clear()
        self.monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
        self.monitor_thread.start()
    
    def stop_monitoring_system(self) -> None:
        """停止性能监控"""
        if self.monitor_thread:
            self.stop_monitoring.set()
            self.monitor_thread.join(timeout=2)
            self.logger.info("性能监控已停止")
    
    def _monitor_loop(self) -> None:
        """监控循环"""
        process = psutil.Process()
        
        while not self.stop_monitoring.wait(self.interval):
            try:
                # 收集系统指标
                cpu_percent = process.cpu_percent()
                memory_info = process.memory_info()
                memory_percent = process.memory_percent()
                
                # 收集磁盘IO指标
                io_counters = process.io_counters()
                disk_read_mb = io_counters.read_bytes / (1024 * 1024)
                disk_write_mb = io_counters.write_bytes / (1024 * 1024)
                
                # 创建性能指标
                metrics = PerformanceMetrics(
                    timestamp=datetime.now(),
                    cpu_percent=cpu_percent,
                    memory_percent=memory_percent,
                    memory_used_mb=memory_info.rss / (1024 * 1024),
                    disk_io_read_mb=disk_read_mb,
                    disk_io_write_mb=disk_write_mb,
                    processing_time=time.time() - self.start_time,
                    files_processed=0,  # 需要外部更新
                    files_generated=0   # 需要外部更新
                )
                
                # 添加到历史记录
                self.metrics_history.append(metrics)
                
                # 限制历史记录大小
                if len(self.metrics_history) > self.max_history:
                    self.metrics_history.pop(0)
                
            except Exception as e:
                self.logger.warning(f"性能监控数据收集失败: {e}")
    
    def start_processing_timer(self) -> None:
        """开始处理计时"""
        self.processing_start_time = time.time()
    
    def record_processing_result(self, files_processed: int, files_generated: int) -> None:
        """记录处理结果"""
        if self.processing_start_time and self.metrics_history:
            processing_time = time.time() - self.processing_start_time
            
            # 更新最新的指标
            if self.metrics_history:
                latest = self.metrics_history[-1]
                latest.files_processed = files_processed
                latest.files_generated = files_generated
                latest.processing_time = processing_time
            
            self.logger.info(f"处理完成: {files_processed} 个文件 -> {files_generated} 个输出，耗时 {processing_time:.2f}秒")
    
    def get_current_metrics(self) -> Dict[str, Any]:
        """获取当前性能指标"""
        if not self.metrics_history:
            return {}
        
        latest = self.metrics_history[-1]
        return {
            'timestamp': latest.timestamp.isoformat(),
            'cpu_percent': latest.cpu_percent,
            'memory_percent': latest.memory_percent,
            'memory_used_mb': latest.memory_used_mb,
            'disk_io_read_mb': latest.disk_io_read_mb,
            'disk_io_write_mb': latest.disk_io_write_mb,
            'processing_time': latest.processing_time,
            'files_processed': latest.files_processed,
            'files_generated': latest.files_generated
        }
    
    def get_performance_summary(self) -> Dict[str, Any]:
        """获取性能摘要"""
        if not self.metrics_history:
            return {}
        
        # 计算平均值
        avg_cpu = sum(m.cpu_percent for m in self.metrics_history) / len(self.metrics_history)
        avg_memory = sum(m.memory_percent for m in self.metrics_history) / len(self.metrics_history)
        max_memory = max(m.memory_used_mb for m in self.metrics_history)
        
        # 计算处理效率
        total_files = sum(m.files_processed for m in self.metrics_history)
        total_generated = sum(m.files_generated for m in self.metrics_history)
        total_time = time.time() - self.start_time
        
        return {
            'monitoring_duration': total_time,
            'avg_cpu_percent': avg_cpu,
            'avg_memory_percent': avg_memory,
            'max_memory_used_mb': max_memory,
            'total_files_processed': total_files,
            'total_files_generated': total_generated,
            'processing_rate': total_files / total_time if total_time > 0 else 0,
            'generation_rate': total_generated / total_time if total_time > 0 else 0,
            'metrics_count': len(self.metrics_history)
        }
    
    def export_metrics(self, filepath: str) -> None:
        """导出性能指标到文件"""
        try:
            import json
            
            data = {
                'summary': self.get_performance_summary(),
                'current': self.get_current_metrics(),
                'history': [
                    {
                        'timestamp': m.timestamp.isoformat(),
                        'cpu_percent': m.cpu_percent,
                        'memory_percent': m.memory_percent,
                        'memory_used_mb': m.memory_used_mb,
                        'processing_time': m.processing_time,
                        'files_processed': m.files_processed,
                        'files_generated': m.files_generated
                    }
                    for m in self.metrics_history
                ]
            }
            
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=2, ensure_ascii=False)
            
            self.logger.info(f"性能指标已导出到: {filepath}")
            
        except Exception as e:
            self.logger.error(f"导出性能指标失败: {e}")